package com.xxk.rocket.star.serialize;

import com.xxk.rocket.star.core.context.ProducerContext;
import com.xxk.rocket.star.core.process.IStargateClientEncod;
import com.xxk.rocket.star.core.vo.StargateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeStargateClientEncode implements IStargateClientEncod {

  private static final Logger log = LoggerFactory.getLogger(SerializeStargateClientEncode.class);

  @Override
  public byte[] encode(StargateMessage stargateMessage, ProducerContext producerContext) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = null;

    try {
      objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      objectOutputStream.writeObject(stargateMessage);
      byte[] bytes = byteArrayOutputStream.toByteArray();
      return bytes;
    } catch (Throwable e) {
      log.error("SerializeRocketClientEncod error:", e);
    } finally {
      try {
        objectOutputStream.close();
      } catch (IOException e) {
        log.error("SerializeRocketClientEncod close error:", e);
      }

    }

    return null;
  }
}
